package loadiconhandler

import (
	"fmt"
	"gmap-backend/internal/config"
	"gmap-backend/internal/server/vo"
	"gmap-backend/internal/util/pathutil"
	"strings"
)

type OpenAsLoadIcon struct {
}

func (owner *OpenAsLoadIcon) CanHandle(appConfig *config.AppConfig, req *vo.PathReq) (bool, any) {
	urlMatch := strings.HasPrefix(req.Path, "openas:///") || strings.HasPrefix(req.Path, "openas://")
	if urlMatch {
		path := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(req.Path, "openas:///"), "openas://"))
		return true, path
	}
	return false, nil
}

// 当为目录时，结果为目录和对勾的叠加
// 当为文件时，结果为文件对应的图标与对勾的叠加
func (owner *OpenAsLoadIcon) Handle(appConfig *config.AppConfig, req *vo.PathReq, extra any) *vo.LoadIconResp {
	path := extra.(string)

	bigImgPath := ""
	if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
		bigImgPath = GetHttpIconUrl(appConfig, path).Url
	} else {
		parseResult := pathutil.ParseValidPath(path, req.CtxDir)
		if !parseResult.Succ {
			panic(fmt.Sprintf("路径不存在：\r\n%s", path))
		}
		if parseResult.Dir {
			panic(fmt.Sprintf("目录不支持打开方式操作：\r\n%s", path))
		}
		bigImgPath = GetFileIconUrl(appConfig, parseResult.ValidPath).Url
	}

	return &vo.LoadIconResp{
		Cascade: true,
		Url:     bigImgPath,
		Url2:    SPECIAL_PATH_MENU,
	}
}
